package com.hnx.admin.aurora.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hnx.admin.aurora.annotation.DataScope;
import com.hnx.admin.aurora.annotation.Log;
import com.hnx.admin.aurora.annotation.Pager;
import com.hnx.admin.aurora.context.LogContext;
import com.hnx.admin.aurora.security.utils.SecurityUtil;
import com.hnx.admin.aurora.system.domain.dto.log.SysOperLogDTO;
import com.hnx.admin.aurora.system.domain.param.dept.form.DeptForm;
import com.hnx.admin.aurora.system.domain.param.log.form.LogForm;
import com.hnx.admin.aurora.system.domain.param.log.query.OperLogQuery;
import com.hnx.admin.aurora.system.domain.vo.emp.entity.EmpVO;
import com.hnx.admin.aurora.system.domain.vo.user.entity.UserDetailVO;
import com.hnx.admin.aurora.system.domain.vo.user.entity.UserVO;
import com.hnx.admin.aurora.system.mapper.log.SysOperlogMapper;
import com.hnx.admin.aurora.system.service.AsyncSysOperLogService;
import com.hnx.admin.aurora.system.service.SysOperlogService;
import com.hnx.admin.aurora.utils.IPUtil;
import com.hnx.admin.aurora.utils.ServletUtil;
import com.hnx.admin.aurora.web.json.ResultJson;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/*
创建人： 倔强的头发
创建时间：2025/6/19
功能描述:

*/
@Service
@RequiredArgsConstructor
public class SysOperlogServiceImpl implements SysOperlogService {
    private final SysOperlogMapper sysOperlogMapper;
    private final AsyncSysOperLogService asyncSysOperLogService;
    @Override
    @DataScope
    @Pager(orderBy = " oper_time desc")
    public ResultJson selectOperLogList(OperLogQuery operLog) {
        List<SysOperLogDTO> list = sysOperlogMapper.selectOperLogList(operLog);
        return ResultJson.success().add("rows",list);
    }

    @Override
    public void export(HttpServletResponse response) {

    }

    @Override
    public void logHandler(JoinPoint joinPoint, Log log, String json, Integer status) {
        UserDetailVO userDetailVO = (UserDetailVO)SecurityUtil.getPrincipal();
        UserVO userVO = userDetailVO.getUserVO();
        DeptForm deptParam = new DeptForm();
        deptParam.setDeptId(userVO.getDept().getDeptId());
        deptParam.setDeptName(userVO.getDept().getDeptName());
        // 设置方法名称
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        HttpServletRequest request = ServletUtil.getRequest();
        String url = request.getRequestURI();
        Object[] args = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (Object obj:args){
            sb.append(JSON.toJSONString(obj));
        }
        LogForm logForm = LogForm.builder()
                .title(log.title())
                .status(status)
                .operUrl(url)
                .operParam(sb.toString())
                .requestMethod(request.getMethod())
                .operIp(IPUtil.getClientIp(request))
                .operName(userVO.getUserName())
                .dept(deptParam)
                .operatorType(log.operatorType().ordinal())
                .businessType(log.businessType().ordinal())
                .costTime(System.currentTimeMillis() - LogContext.getTime())
                .method(className + "." + methodName + "()")
                .build();
        EmpVO emp = userVO.getEmp();
        if(Objects.nonNull(emp)){
            logForm.setUserId(emp.getUserId());
            logForm.setDeptId(emp.getDeptId());
        }
        if(status == 0){
            logForm.setJsonResult(json);
        }
        else {
            logForm.setErrorMsg(json);
        }
        asyncSysOperLogService.insertOperlog(logForm);
        LogContext.clear();
    }
}
